package ManagerImage.entity;

import ManagerImage.Utils.IconUtil;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.Duration;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class SlideShow {
    IconUtil iconUtil=new IconUtil();
    private int currentIndex=0; // 当前显示的图片索引
    private boolean isPlaying = false; // 记录播放状态
    private Timeline timeline=null; // 定义时间线
    public SlideShow(File selectedImage) {
        File directory = selectedImage.getParentFile();
        List<File> imagesInDirectory = loadImagesFromDirectory(directory.getAbsolutePath());
        currentIndex = imagesInDirectory.indexOf(selectedImage); // 获取当前图片索引

        ImageView imageView = new ImageView(new Image(selectedImage.toURI().toString()));
        imageView.setFitWidth(800);
        imageView.setFitHeight(600);
        //确保在调整图像的大小时维持图像的宽高比
        imageView.setPreserveRatio(true);

        // 创建前后切换按钮

        Button previousButton = new Button("上一张");
        iconUtil.setIconInButton(previousButton,new Image("resource/left.png"));
        previousButton.setOnAction(e -> {
            if (currentIndex > 0) {
                currentIndex--;
                updateImage(imageView, imagesInDirectory.get(currentIndex));
            }else {
                showAlert("提示", "已经是第一张图片了");
            }
        });
        Button nextButton = new Button("下一张");
        iconUtil.setIconInButton(nextButton,new Image("resource/right.png"));
        nextButton.setOnAction(e -> {
            if (currentIndex < imagesInDirectory.size() - 1) {
                currentIndex++;
                updateImage(imageView, imagesInDirectory.get(currentIndex));
            }else {
                showAlert("提示", "已经是最后一张图片了");
            }
        });

        // 创建播放和停止按钮

        Button playButton = new Button("播放");
        iconUtil.setIconInButton(playButton,new Image("resource/play.png"));
        playButton.setOnAction(e -> startSlideshow(imageView, imagesInDirectory));
        Button stopButton = new Button("停止");
        iconUtil.setIconInButton(stopButton,new Image("resource/stop.png"));
        stopButton.setOnAction(e -> stopSlideshow());

        // 创建放大和缩小按钮

        Button zoomInButton = new Button("放大");
        iconUtil.setIconInButton(zoomInButton,new Image("resource/zoom-in.png"));
        zoomInButton.setOnAction(e -> zoomImage(imageView, 1.2)); // 放大20%
        Button zoomOutButton = new Button("缩小");
        iconUtil.setIconInButton(zoomOutButton,new Image("resource/zoom-out.png"));
        zoomOutButton.setOnAction(e -> zoomImage(imageView, 0.8)); // 缩小20%

        // 创建StackPane布局->实现我的按钮条hbox始终处于图层最上层

        StackPane slideShowRoot = new StackPane(); // 使用 StackPane
        // 创建 HBox 放置控制按钮
        HBox hBox = new HBox();
        hBox.setPrefHeight(40);
        hBox.setAlignment(Pos.BOTTOM_CENTER);
        hBox.getChildren().addAll(playButton, stopButton, zoomInButton, zoomOutButton, previousButton, nextButton);
        // 将 HBox 添加到 StackPane，确保其位于最上层
        slideShowRoot.getChildren().add(imageView); // 将 ImageView 添加到 StackPane
        slideShowRoot.getChildren().add(hBox);//再将hBox添加到StackPane，实现栈布局的最高覆盖

        // 创建舞台并显示场景
        Stage slideShowStage = new Stage();
        Scene slideShowScene = new Scene(slideShowRoot, 1000, 800);

        //idea运行用这句!!!!!!
        slideShowScene.getStylesheets().add(getClass().getResource("../styles.css").toExternalForm()); // 加载 CSS 文件
        //window命令行打包用这句
        //slideShowScene.getStylesheets().add(getClass().getResource("/styles.css").toExternalForm());
        slideShowStage.setTitle("图片浏览");
        slideShowStage.setScene(slideShowScene);
        slideShowStage.show();
    }
    //返回一个只含有图片的文件夹列表
    private List<File> loadImagesFromDirectory(String directoryPath) {
        File directory = new File(directoryPath);
        File[] files = directory.listFiles((dir, name) -> name.toLowerCase().endsWith(".jpg") ||
                name.toLowerCase().endsWith(".png") ||
                name.toLowerCase().endsWith(".gif"));
        List<File> images = new ArrayList<>();
        if (files != null) {
            for (File file : files) {
                images.add(file);
            }
        }
        return images;
    }
    //更新图片
    private void updateImage(ImageView imageView, File imageFile) {
        imageView.setImage(new Image(imageFile.toURI().toString()));
    }
    //提示窗口
    private void showAlert(String title, String message) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }
    //播放事件
    private void startSlideshow(ImageView imageView, List<File> imagesInDirectory) {
        if (isPlaying) return; // 如果已经在播放则不再开始
        isPlaying = true;
        // 创建时间线
        timeline = new Timeline(new KeyFrame(Duration.seconds(1), e -> {
            //检查当前索引是否小于最后一张图片的索引
            if (currentIndex < imagesInDirectory.size() - 1) {
                currentIndex++;
            } else {
                currentIndex = 0; // 循环播放
            }
            updateImage(imageView, imagesInDirectory.get(currentIndex));
        }));
        timeline.setCycleCount(Timeline.INDEFINITE); // 设置为无限循环
        timeline.play(); // 开始播放
        // 禁用其他按钮（暂时未实现）
        disableControls(true);
    }
    //播放停止事件
    private void stopSlideshow() {
        if (timeline != null) {
            timeline.stop(); // 停止播放
            isPlaying = false; // 更新播放状态
        }
        disableControls(false); // 启用其他按钮
    }

    // 禁用其他按钮（暂时未实现）
    private void disableControls(boolean disable) {
        // 禁用或启用所有控制按钮（根据需要添加更多按钮）
    }
    //放大缩小事件
    private void zoomImage(ImageView imageView, double scaleFactor) {
        // 获取当前图片的宽度和高度
        double currentWidth = imageView.getFitWidth();
        double currentHeight = imageView.getFitHeight();
        // 设置新的宽度和高度
        imageView.setFitWidth(currentWidth * scaleFactor);
        imageView.setFitHeight(currentHeight * scaleFactor);
    }
}
